package com.allwees.bs.c.module.user.controller;

import com.allwees.bs.c.module.base.controller.BaseController;
import com.allwees.bs.c.module.share.req.ShareAccessReq;
import com.allwees.bs.c.module.share.req.ShareGenReq;
import com.allwees.bs.c.module.share.req.ShareSuccessReq;
import com.allwees.bs.c.module.share.util.ShareEncryptor;
import com.allwees.bs.c.module.user.entity.UserEntity;
import com.allwees.bs.c.module.user.service.IShareService;
import com.allwees.bs.c.module.user.service.IUserService;
import com.allwees.bs.core.model.constant.EPromotionChannel;
import com.allwees.bs.core.model.product.constant.EProductStatItemType;
import com.allwees.bs.core.model.product.mq.event.ProductStatItemEvent;
import com.allwees.bs.core.model.product.mq.event.model.ProductStatItemInfo;
import com.allwees.bs.core.model.share.bo.ShareBo;
import com.allwees.bs.core.modelbase.vo.R;
import com.allwees.core.common.constant.EPlatform;
import com.allwees.core.common.util.http.RequestUtil;
import com.allwees.core.common.util.json.JsonUtil;
import com.allwees.core.mq.rabbitmq.MqUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 分享
 *
 * @author yangylsky
 */
@RestController
@RequestMapping("/api/v1/share")
@Validated
public class ShareController extends BaseController {
    @Autowired
    private IUserService userService;

    @Autowired
    private IShareService shareService;

    @Value("${allwees.pcBasePath}")
    private String pcBasePath;

    @Value("${allwees.mobileBasePath}")
    private String mobileBasePath;

    /**
     * 获取Facebook商品分享链接
     *
     * @throws IOException
     */
    @GetMapping("/facebook/product/{productUuid}")
    public ModelAndView facebookShareProduct(HttpServletRequest request, HttpServletResponse response,
                                             @PathVariable("productUuid") String productUuid) throws IOException {
        String userAgent = request.getHeader("user-agent");
        if (StringUtils.contains(userAgent, "facebookexternalhit")) {
            ModelAndView mv = new ModelAndView();
            mv.addObject("data", shareService.shareProduct(request.getRequestURL().toString(), productUuid));
            mv.setViewName("share");
            return mv;
        } else {
            response.sendRedirect(mobileBasePath + "/product/info/" + productUuid);
            return null;
        }
    }

    /**
     * 获取分享地址
     *
     * @param request
     * @param req
     * @return
     */
    @PostMapping("/gen_share_url")
    public R genShareUrl(HttpServletRequest request, @RequestBody @Validated ShareGenReq req) {
        String userUuid = getUserUuid();
        req.setSharerUuid(userUuid);
        req.setIp(RequestUtil.getIpFromRequest(request));
        ShareBo shareBo = req.toShareBo();
        if (StringUtils.isNotBlank(userUuid)) {
            UserEntity user = userService.findByUserUuid(userUuid);
            shareBo.setShareCode(user.getShareCode());
        }
        String shareUrl = buildShareUrl(shareBo);
        Map<String, Object> data = new HashMap<String, Object>() {{
            put("type", shareBo.getType().name());
            put("platform", shareBo.getPlatform().name());
            put("k", shareBo.getBsKey());
            put("shareUrl", shareUrl);
            put("s_uid", shareBo.getUuid());
            put("sr_uid", shareBo.getSharerUuid());
            put("sr_code", shareBo.getShareCode());
        }};
        return R.ok(data);
    }

    private String buildShareUrl(ShareBo shareBo) {
        String encryptUrl = ShareEncryptor.encrypt(JsonUtil.toJson(shareBo));
        String shareUrl = genShareUrlPrefix(shareBo) + "?d=" + encryptUrl
                + "&channel=" + EPromotionChannel.FACKBOOK
                + "&s_uid=" + (StringUtils.isNotBlank(shareBo.getUuid()) ? shareBo.getUuid() : "")
                + "&sr_uid=" + (StringUtils.isNotBlank(shareBo.getSharerUuid()) ? shareBo.getSharerUuid() : "")
                + "&sr_code=" + (StringUtils.isNotBlank(shareBo.getShareCode()) ? shareBo.getShareCode() : "")
                + "&platform=" + shareBo.getPlatform()
                + "&type=" + shareBo.getType()
                + "&k=" + shareBo.getBsKey();
        return shareUrl;
    }

    private String genShareUrlPrefix(ShareBo shareBo) {
        String basePath = EPlatform.PC.equals(shareBo.getPlatform()) ? pcBasePath : mobileBasePath;
        switch (shareBo.getType()) {
            case PROD:
                return basePath + "/product/info/" + shareBo.getBsKey();
            case REG:
            default:
                throw new IllegalArgumentException(shareBo.getType().name());
        }
    }

    /**
     * 分享成功回调
     *
     * @param req
     * @param shareReq
     * @return
     */
    @PostMapping("/share_success")
    public R shareSuccess(HttpServletRequest req, @RequestBody @Validated ShareSuccessReq shareReq) {
        shareReq.setIp(RequestUtil.getIpFromRequest(req));
        MqUtil.send(new ProductStatItemEvent(new ProductStatItemInfo(EProductStatItemType.SHARE, shareReq.getK())));
        return R.ok();
    }

    /**
     * 点击分享链接的访问上报
     *
     * @param req
     * @param shareReq
     * @return
     */
    @PostMapping("/share_access")
    public R shareAccess(HttpServletRequest req, @RequestBody @Validated ShareAccessReq shareReq) {
        return R.ok();
    }
}
